import re
import time
from flask import request
from flask_restful import abort
from flask_login import current_user, login_user
from funcy import project
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.exc import IntegrityError
from funcy import partial

from redash import models, limiter
from redash.permissions import (
    require_admin,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
    get_object_or_404,
    paginate,
    order_results as _order_results,
)

from redash.authentication.account import (
    invite_link_for_user,
    send_invite_email,
    send_password_reset_email,
    send_verify_email,
)
from redash.settings import parse_boolean
from redash import settings



class Workflow_bill_stateNewResource(BaseResource):
    @require_admin
    def post(self):
        req = request.get_json(force=True)
        require_fields(req, ("workflowid","workflow_stateid"))

        workflow_bill_state = models.Workflow_bill_state(
        userid=req["userid"],
        org=self.current_org,
        docstatus = req["docstatus"],
        workflowid=req["workflowid"],
        workflow_stateid=req["workflow_stateid"],
        billid = req["billid"],
        bill_enum = req["bill_enum"],
        bill_type = req["bill_type"],
        allow_user =  req["allow_user"],
        allow_group =req["allow_group"],
        allow_col =req["allow_col"],
        message =req["message"],
        is_active= req["is_active"],
        )
        try:
            models.db.session.add(workflow_bill_state)
            models.db.session.commit()
        except IntegrityError as e:
            if "name" in str(e):
                abort(400, message="编号已存在.")
            abort(500)

        # timeserial.record_event(
        #     {"action": "create", "object_id": timeserial.id, "object_type": "timeserial"}
        # )

class Workflow_bill_stateResource(BaseResource):
    def get(self, workflow_bill_state_id):
        result = models.Workflow_bill_state.get_by_id(workflow_bill_state_id)
        return result.to_dict()

    @require_admin
    def post(self, workflow_bill_state_id):
        req = request.get_json(force=True)
        require_fields(req, ("workflowid","workflow_stateid"))

        workflow_bill_state = models.Workflow_bill_state.get_by_id(workflow_bill_state_id)
        params = dict(docstatus = req["docstatus"],workflowid=req["workflowid"],workflow_stateid=req["workflow_stateid"],
        billid = req["billid"],bill_enum = req["bill_enum"],bill_type = req["bill_type"],allow_user =  req["allow_user"],
        allow_group =req["allow_group"],allow_col =req["allow_col"],message =req["message"],is_active= req["is_active"])
        try:
            self.update_model(workflow_bill_state, params)
            models.db.session.commit()
        except IntegrityError as e:
            if "name" in str(e):
                abort(400, message="名称已存在.")
            abort(500)

class Workflow_bill_statedeleteResource(BaseResource):
    @require_admin
    def post(self, workflow_bill_state_id):
        workflow_bill_state =  models.Workflow_bill_state.get_by_id(workflow_bill_state_id)
        models.db.session.delete(workflow_bill_state)
        models.db.session.commit()

class Workflow_bill_stateListResource(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        page = req["page"]
        page_size = req["pagesize"]
        name = req["name"]
        billid = str(req["billid"])
        strwhere ="t1.org_id=" +str(self.current_org.id)
        if name !='' :
            strwhere = strwhere + " and t2.name like '%"+name+"%'"

        if billid !='' :
            strwhere = strwhere + " and t1.billid = "+billid+""
        strgetfield ="""  t1.*,t2.name,
          array(SELECT name FROM users WHERE id = ANY(t1.allow_user)) username,
          array(SELECT name FROM groups WHERE id = ANY(t1.allow_group)) groupname"""

        tblname = """ workflow_bill_state t1 left join workflow_state t2 on t1.workflow_stateid = t2.id  """
        orderfield ="t1.id"
        result = models.ContractApply.get_pagequery(tblname,strgetfield,orderfield,page_size,page,0,strwhere)
        return result[0]
